package me.idashu.attg.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import me.idashu.attg.domain.ContextEntity;
import me.idashu.attg.domain.ContributionEntity;
import me.idashu.attg.domain.PageEntity;
import me.idashu.attg.domain.RecommendsDataStatisticsEntity;
import me.idashu.attg.service.ContributionService;
import me.idashu.attg.util.SystemConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/contribution")
public class ContributionController {

	private ContributionService contributionService;
	
	private SystemConfig systemConfig;

	@Autowired
	public void setContributionService(ContributionService contributionService) {
		this.contributionService = contributionService;
	}

	@RequestMapping("/contributionList")
	public String contributionList(Model model) {
		Map<String, Object> map = new HashMap<String, Object>();
		int total = contributionService.contributionCount(0);
		PageEntity pageEntity = new PageEntity();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<ContributionEntity> contributionList = contributionService
				.contributionsList(map);
		if (contributionList.size() <= 0) {
			contributionList = null;
		}
		model.addAttribute("listContribution", "投稿列表");
		model.addAttribute("contributionList", contributionList);
		model.addAttribute("pageEntity", pageEntity);
		return "contribution_list";
	}

	public void selectContributions(Model model, ContextEntity contextEntity,
			PageEntity pageEntity) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = contributionService
				.contributionCount(contextEntity.getId());
		pageEntity.setTotalPage(count);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		map.put("id", contextEntity.getId());
		List<ContributionEntity> contributions = contributionService
				.contributionsList(map);
		if (contributions == null || contributions.size() == 0) {
			model.addAttribute("contributions", null);
		} else {
			model.addAttribute("contributions", contributions);
		}
		model.addAttribute("pageEntity", pageEntity);
	}

	@RequestMapping("/updateContributionFlag")
	public String updateContributionFlag(
			@ModelAttribute ContributionEntity contributionEntity,
			@ModelAttribute PageEntity pageEntity, Model model) {
		contributionService.updateContributionFlag(contributionEntity);
		ContextEntity contextEntity = new ContextEntity();
		contextEntity.setId(contributionEntity.getContext_id());
		selectContributions(model, contextEntity, pageEntity);
		return "contributions";
	}

	@RequestMapping("/deleteContribution")
	public String deleteContribution(
			@RequestParam("contributionId") int contributionId, Model model) {
		contributionService.deleteContribution(contributionId);
		contributionList(model);
		return "contribution_list";
	}

	@RequestMapping("/contributionDataStatistics")
	public String contributionDataStatistics(Model model){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = contributionService.countContribution();
		PageEntity pageEntity = new PageEntity();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<ContributionEntity> contributionList = contributionService.contributionDataStatistics(map);
		if(contributionList.size()<=0){
			contributionList = null;
		}
		model.addAttribute("listContribution", "投稿数据统计");
    	model.addAttribute("contributionList", contributionList);
    	model.addAttribute("pageEntity", pageEntity);
		return "contribution_datastatistics";
	}
	
	@RequestMapping("/contributionDataStatisticsAjaxList")
	public String contributionDataStatisticsAjaxList(Model model,@ModelAttribute PageEntity pageEntity){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = contributionService.countContribution();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<ContributionEntity> contributionList = contributionService.contributionDataStatistics(map);
		if(contributionList.size()<=0){
			contributionList = null;
		}
		model.addAttribute("listContribution", "投稿数据统计");
    	model.addAttribute("contributionList", contributionList);
    	model.addAttribute("pageEntity", pageEntity);
		return "contribution_datastatistics";
	}
	
	@RequestMapping("/contributionPartExport")
	public void contributionPartExport(@RequestParam("dateFrom") String dateFrom,@RequestParam("dateTo") String dateTo,HttpServletResponse response){
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			dateFrom = dateFrom+" 00:00:00";
			dateTo = dateTo+" 23:59:59";
			map.put("dateFrom", dateFrom);
			map.put("dateTo", dateTo);
			List<ContributionEntity> contributionList = contributionService.contributionDataStatistics(map);
//			String xlsPath = systemConfig.getDir("xlsPath");
			String xlsPath = "E:/投稿数据统计.xls";
			toXLS(contributionList, xlsPath);
			downloadFile(new File(xlsPath),"result.xls",response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/contributionExport")
	public void contributionExport(HttpServletResponse response){
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dateFrom", "");
			map.put("dateTo", "");
			List<ContributionEntity> contributionList = contributionService.contributionDataStatistics(map);
//			String xlsPath = systemConfig.getDir("xlsPath");
			String xlsPath = "E:/投稿数据统计.xls";
			toXLS(contributionList, xlsPath);
			downloadFile(new File(xlsPath),"result.xls",response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/contributionDetails")
	public String contributionDetails(Model model,@RequestParam("id") int id){
		try {
			List<ContributionEntity> contributionEntity = contributionService.getContributionById(id);
			model.addAttribute("contributionEntity", contributionEntity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "contributionAjaxList";
	}
	
	public void toXLS(Collection collection,String path) {   
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			WritableWorkbook book = Workbook.createWorkbook(new File(path));
			WritableSheet sheet = book.createSheet("导出数据", 0);
			Label labe1 = new Label(0, 0, "投稿日期");
			Label labe2 = new Label(1, 0, "投稿人");
			Label labe3 = new Label(2, 0, "待审核");
			Label labe4 = new Label(3, 0, "发布");
			Label labe5 = new Label(4, 0, "已审核待定");
			Label labe6 = new Label(5, 0, "投稿板块");
			
			sheet.addCell(labe1);
			sheet.addCell(labe2);
			sheet.addCell(labe3);
			sheet.addCell(labe4);
			sheet.addCell(labe5);
			sheet.addCell(labe6);
			
			Iterator it = collection.iterator();
			int i = 1;
			while(it.hasNext()) {
				ContributionEntity srrf = (ContributionEntity) it.next();
				Label label1 = new Label(0, i, sdf.format(srrf.getTime()));
				Label label2 = new Label(1, i, srrf.getUsername());
				Label label3 = null;
				Label label4 = null;
				Label label5 = null;
				if("N".equals(srrf.getFlag())){
					label3 = new Label(2, i, "√");
				}else{
					label3 = new Label(2, i, "");
				}
				if("Y".equals(srrf.getFlag())){
					label4 = new Label(3, i, "√");
				}else{
					label4 = new Label(3, i, "");
				}
				if("N1".equals(srrf.getFlag())){
					label5 = new Label(4, i, "√");
				}else{
					label5 = new Label(4, i, "");
				}
				Label label6 = new Label(5, i, srrf.getTitle());
				
				sheet.addCell(label1);
				sheet.addCell(label2);
				sheet.addCell(label3);
				sheet.addCell(label4);
				sheet.addCell(label5);
				sheet.addCell(label6);
				i++;
			}
			book.write();
			book.close();
		} catch (Exception e) {    
			
			e.printStackTrace();    
		}
	}
	protected void downloadFile(File file,String fileName,
			HttpServletResponse response) throws Exception {
		response.setContentType("application/oct-stream;charset=UTF-8");
		response.setHeader("Content-disposition",
				"attachment;filename="+fileName);
		BufferedInputStream in = new BufferedInputStream(new
				FileInputStream(file));
		BufferedOutputStream out = new BufferedOutputStream(response.
				getOutputStream());
		byte[] buff = new byte[4096];
		int length = -1;
		while ((length = in.read(buff)) != -1) {
			out.write(buff, 0, length);
		}
		in.close();
		out.close();
	}
}
